﻿
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.IO
Imports System.Management
Imports System.Diagnostics
Imports System.ComponentModel
Imports Microsoft.Web.Administration
Imports Microsoft.Web.Management
Imports System.Security
Imports System.Net.NetworkInformation
Imports System.Net
Imports System.Xml
Imports System.Data.SqlClient




Public Class Monitor

    Dim m_strServerName As String

    Public Property ServerName As String
        Get
            Return m_strServerName
        End Get
        Set(value As String)
            m_strServerName = value
        End Set
    End Property

    Private Const MSSystem As String = "\C$\SecretAgent\wwwRoot\IncludeDirectories\Mastersite\System\"

    Private Sub RunProcess(ServerName As String, process As String)
        Dim theProcessToRun As Object() = {process}
        Dim mClass As New ManagementClass("\\" & ServerName & "\root\cimv2:Win32_Process")
        Dim result As Object = mClass.InvokeMethod("Create", theProcessToRun)
    End Sub

    'This will reset the IIS for the server. 
    Public Function IISReset() As [Boolean]
        Try
            RunProcess(ServerName, "iisreset.exe")
            Return True
        Catch
            Return False
        End Try
    End Function

    'Takes server offline
    Public Function ServerOffline()
        Dim Value
        Try

            ServerName = "\\" & ServerName
            File.SetAttributes(ServerName & MSSystem & "Status.aspx", FileAttributes.Normal)
            File.Delete(ServerName & MSSystem & "Status.aspx")
            File.Copy(ServerName & MSSystem & "StatusFail.aspx", ServerName & MSSystem & "Status.aspx")

            Value = "Offline"
            Return Value

        Catch


            Value = "Error"
            Return Value
        End Try
    End Function

    'Brings server online
    Public Function ServerOnline()
        Dim Value As String
        Try
            ServerName = "\\" & ServerName
            File.SetAttributes(ServerName & MSSystem & "Status.aspx", FileAttributes.Normal)
            File.Delete(ServerName & MSSystem & "Status.aspx")
            File.Copy(ServerName & MSSystem & "StatusOriginal.aspx", ServerName & MSSystem & "Status.aspx")

            Value = "Online"
            Return Value
        Catch
            Value = "Error"
            Return Value

        End Try
    End Function

    'Pulls the performance counter for that specfic server. 
    Public Function PerformanceMonitor(Name As String, PW As String, counter As String) As String

        Dim ReturnCounter As String = ""
        Try
            Dim connection As New ConnectionOptions()
            connection.Username = Name
            connection.Password = PW
            connection.Authority = "ntlmdomain:ENEIGHBORHOODS"

            Dim scope As New ManagementScope("\\" & ServerName & "\root\CIMV2", connection)
            scope.Connect()

            Dim query As New ObjectQuery("SELECT * FROM Win32_PerfRawData_ASPNET_ASPNETApplications")
            Dim query1 As New ObjectQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory")
            Dim query2 As New ObjectQuery("SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk")

            Dim searcher As New ManagementObjectSearcher(scope, query)



            For Each queryObj As ManagementObject In searcher.[Get]()
                If counter = "1" Then
                    '"AnonymousRequests : {0}"
                    ReturnCounter = ("AnonymousRequests: " + queryObj("AnonymousRequests").ToString())
                    '"AnonymousRequests : {0}"
                    Debug.WriteLine(queryObj("AnonymousRequests"))
                    Exit For
                End If

                If counter = "2" Then
                    '"RequestExecutionTime : {0}"
                    ReturnCounter = ("RequestExecutionTime: " + queryObj("RequestExecutionTime").ToString())
                    Exit For
                End If

                If counter = "3" Then
                    '"RequestWaitTime : {0}"
                    ReturnCounter = ("RequestWaitTime: " + queryObj("RequestWaitTime").ToString())
                    Exit For
                End If

                If counter = "4" Then
                    '"AnonymousRequestsPerSec : {0}"
                    ReturnCounter = ("AnonymousRequestsPerSec" + queryObj("AnonymousRequestsPerSec").ToString())
                    Exit For
                End If

                If counter = "5" Then
                    ' "SessionActive : {0}"
                    ReturnCounter = ("SessionActive: " + queryObj("SessionActive").ToString())
                    Exit For
                End If
            Next



            If counter = "6" Then
                Dim searcher3 As New ManagementObjectSearcher(scope, query2)


                For Each queryObj As ManagementObject In searcher3.[Get]()

                    If True Then
                        '"AvgDiskQueueLength : {0} "
                        ReturnCounter = ("AvgDiskQueueLength" + queryObj("AvgDiskQueueLength").ToString())
                        Exit For
                    End If
                Next
            End If




        Catch err As ManagementException

            ReturnCounter = err.Message.ToString()
        End Try

        Return ReturnCounter
    End Function

    'Connects to the Database NFDBCONFIF\\CONFIG
    Public Function SerNames() As List(Of String)
        'Initating a new list for the ilist the combo box takes. 
        Dim ServerList As New List(Of String)()
        Dim queryString As String = "usp_Get_WebDronePair;"
        Dim thisconnection As New SqlConnection("Data Source=NFDBCONFIG\CONFIG;" & "Initial Catalog=Customers;" & "user id=rciapplicationsnew;" & "password=H7hr89jz?")

        If True Then

            Dim command As New SqlCommand(queryString, thisconnection)
            thisconnection.Open()

            Dim reader As SqlDataReader = command.ExecuteReader()

            While reader.Read()


                ServerList.Add(reader("WebServerName").ToString())
            End While

            thisconnection.Close()

        End If
        Return ServerList
    End Function

    'Web Server Status.
    Public Function CheckPool()
        Dim ResponseWebSite As String = " "
        Dim WebSiteLink As String
        Dim html As String = " "


        Try

            WebSiteLink = "http://" & ServerName.ToLower() & "/system/status.aspx"

            html = New TimeClass() With {.Timeout = 5000}.DownloadString(WebSiteLink)

        Catch generatedExceptionName As WebException
            WebSiteLink = "http://www." & ServerName.ToLower() & ".com/system/status.aspx"

            html = New TimeClass() With {.Timeout = 150000}.DownloadString(WebSiteLink)
        End Try

        Try


            Dim intPos As Integer = html.IndexOf("All OK")

            If html.Contains("True") Then
                ResponseWebSite = "OK"

            ElseIf html.Contains("False") Then
                ResponseWebSite = "NOT OK"
            End If

        Catch
            ResponseWebSite = "Not Reachable"
        End Try

        Return ResponseWebSite

    End Function

    'Check if Attentnion is need to a specicifc server. 
    Public Function CheckAttenion()
        Dim ResponseWebSite As String = " "
        Dim WebSiteLink As String
        Dim html As String = " "
        Try

            WebSiteLink = "http://" & ServerName.ToLower() & "/system/status.aspx"

            html = New TimeClass() With {.Timeout = 5000}.DownloadString(WebSiteLink)
        Catch generatedExceptionName As WebException
            WebSiteLink = "http://www." & ServerName.ToLower() & ".com/system/status.aspx"

            html = New TimeClass() With {.Timeout = 150000}.DownloadString(WebSiteLink)
        End Try

        Try


            Dim intPos As Integer = html.IndexOf("Needs Attention")

            If html.Contains("Yes") Then
                ResponseWebSite = "Yes"

            ElseIf html.Contains("No") Then
                ResponseWebSite = "No"
            End If

        Catch
            ResponseWebSite = "Not Reachable"
        End Try

        Return ResponseWebSite

    End Function

    Public Sub New(newServerName As String)
        m_strServerName = newServerName
    End Sub

    

End Class